<template>
  <div class="problem-detail">
    <c-table-box hide-func class="table-span" auto-height unfold :table-span-method="tableSpanMethod" :table-height="400" :data="comData" :table-config="tableConfig">
      <template v-if="showBtn" #btn>
        <el-popover
          v-model="visible1"
          placement="top"
          width="160"
        >
          <p>生成报告之前，保存除附件外的操作数据?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible1 = false">取消</el-button>
            <el-button type="primary" size="mini" @click="clickGenHandle">确定</el-button>
          </div>
          <c-button slot="reference" gen-pdf="gen-pdf-hide" type="primary">生成验收报告</c-button>
        </el-popover>

        <el-popover
          v-show="$route.query.acceptType&&$route.query.acceptType==='SOFT'"
          v-model="visible2"
          style="margin-left:20px"
          placement="top"
          width="160"
        >
          <p>生成指令单之前，保存除附件外的操作数据?</p>
          <div style="text-align: right; margin: 0">
            <el-button size="mini" type="text" @click="visible2 = false">取消</el-button>
            <el-button type="primary" size="mini" @click="clickPdfHandle">确定</el-button>
          </div>
          <c-button slot="reference" gen-pdf="gen-pdf-hide" type="primary">生成整改指令单</c-button>
        </el-popover>
      </template>
    </c-table-box>
    <!-- <qup-grid-print
      ref="gridPrint"
      @printCallback="printCallback"
    /> -->
    <!-- <print-report v-if="showPrint" :id="detail.id" :visible.sync="showPrint" /> -->
  </div>
</template>
<script>
// import QupGridPrint from 'qup-grid-print'
// import printReport from './printReport.vue'

// import { templateData } from './data.js' // demo使用本地模拟数据 （正式开发时一般从接口获取）
import { sortArr } from '@/utils/mergeArr'

import { getProblemDetailList, getDutyAndProblemlist, getSoftProblemList } from '@/api/check'
export default {
  name: 'ProblemDetail',
  components: { },

  // components: { QupGridPrint, printReport },
  props: {
    showBtn: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: ''
    },
    isValid: {
      type: Boolean,
      default: false
    },
    accType: {
      type: String,
      default: ''
    },
    range: {
      type: String,
      default: ''
    },
    detail: {
      type: Object,
      default: () => {}
    },
    data: {
      type: Array,
      default: () => []
    },
    preview: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      genPdf: false,
      tableData: [],
      // showPrint: false,
      visible1: false,
      visible2: false,
      tableConfig: {
        interfacePath: '',
        setting: [
          {
            prop: 'belongDuty',
            label: '责任归属',
            width: 100
          },
          {
            prop: 'acceptResult',
            label: '验收结果',
            width: 120,
            render: (h, row) => {
              if (!this.genPdf && !this.preview) {
                return h('c-dict-select', {
                  props: {
                    dictTypeCode: 'ACCEPT_RESULT',
                    value: row.acceptResult,
                    disabled: true
                  },
                  attrs: {
                    disabled: true
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'acceptResult', v)
                    },
                    change: v => {
                      this.setValueByCDID(row, { acceptResult: v })
                    }
                  }
                })
              }
              return [h('c-dict-range-view', { style: {
                whiteSpace: 'break-spaces',
                wordBreak: 'break-all',
                width: '100%'
              }, props: { dictTypeCode: 'ACCEPT_RESULT', value: row.acceptResult }})]
            }
          },
          {
            prop: 'principalName',
            label: '责任人',
            width: 140,
            render: (h, row) => {
              if (!this.genPdf && !this.preview) {
                return h('input-with-dialog', {
                  props: {
                    value: row.list,
                    label: row.principalName,
                    props: { label: 'userName', value: 'account' }
                  },
                  attrs: {
                    focusQuery: true,
                    multiple: true,
                    config: {
                      title: '责任人',
                      width: '600px',
                      interfacePath: `/slm-admin/api/v1/user/domainUser/page`,
                      method: 'post',
                      filtersRaw: [],
                      paramsRaw: {},
                      setting: [
                        { prop: 'account', title: '编码', width: 80 },
                        { prop: 'userName', title: '名称', width: 200 },
                        { prop: 'orgName', title: '组织', width: 200 }
                      ]
                    }
                  },
                  on: {
                    change: v => {
                      this.setPrincipalValue(row, v)
                    }
                  }
                })
              }
              return [h('div', { style: {
                whiteSpace: 'break-spaces',
                wordBreak: 'break-all',
                width: '100%'
              }}, row.principalName)]
            }
          },
          {
            prop: 'mustRectifyEndTime',
            label: '应整改完成时间',
            width: 140,
            render: (h, row) => {
              if (!this.genPdf && this.showMustRectifyEndTime(row) && !this.preview) {
                return h('el-date-picker', {
                  props: {
                    type: 'date',
                    format: 'yyyy-MM-dd',
                    valueFormat: 'yyyy-MM-dd HH:mm:ss',
                    placeholder: '选择日期',
                    clearable: true,
                    value: row.mustRectifyEndTime
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'mustRectifyEndTime', v)
                    },
                    change: v => {
                      this.setValueByCDID(row, { mustRectifyEndTime: v })
                    }
                  }
                })
              }
              const formatData = this.$parseTimeYMD('mustRectifyEndTime')
              return [h('div', { style: {
                whiteSpace: 'break-spaces',
                wordBreak: 'break-all',
                width: '100%'
              }}, formatData(row))]
            }
          },
          {
            prop: 'problemClass',
            label: '问题分类',
            width: 100
          },
          {
            prop: 'haveProblem',
            label: '是否存在问题',
            minWidth: 120,
            render: (h, row) => {
              if (!this.genPdf && !this.preview) {
                const child = [
                  h('el-radio', { props: { label: 1 }}, '是'),
                  h('el-radio', { props: { label: 0 }}, '否')
                ]
                return h('el-radio-group', {
                  props: { value: row.haveProblem },
                  on: {
                    input: v => { row.haveProblem = v },
                    change: v => {
                      this.setAcceptResult(v, row)
                      if (v === 0 || v === '0') {
                        this.$set(row, 'problemDesc', '')
                      }
                    }
                  }
                }, child)
              }
              return [h('c-dict-range-view', { style: {
                whiteSpace: 'break-spaces',
                wordBreak: 'break-all',
                width: '100%'
              }, props: { dictTypeCode: 'BOOLEANS', value: (row.haveProblem || '').toString() }})]
            }
          },
          {
            prop: 'problemDesc',
            label: '验收问题说明',
            minWidth: 210,
            render: (h, row) => {
              // <el-input v-model="formData.customerConfirmAdvice" type="textarea"
              //  :autosize="{minRows: 3}"
              //  maxlength="1024" show-word-limit placeholder="确认意见" clearable />
              if (!this.genPdf && !this.preview) {
                return [h('el-input', {
                  props: {
                    value: row.problemDesc,
                    type: 'textarea',
                    autosize: {
                      minRows: 1
                    },
                    disabled: !row.haveProblem,
                    maxlength: 1024,
                    showWordLimit: true,
                    placeholder: '验收问题说明',
                    clearable: true
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'problemDesc', v)
                    }
                  }
                })]
              }
              return [h('div', { style: {
                whiteSpace: 'break-spaces',
                wordBreak: 'break-all',
                width: '100%'
              }}, row.problemDesc)]
            }
          },
          // {
          //   prop: 'haveRectifyItem',
          //   label: '是否存在整改项',
          //   minWidth: 120,
          //   render: (h, row) => {
          //     const child = [
          //       h('el-radio', { props: { label: 1 }}, '是'),
          //       h('el-radio', { props: { label: 0 }}, '否')
          //     ]
          //     return h('el-radio-group', {
          //       props: { value: row.haveRectifyItem },
          //       on: { input: v => { row.haveRectifyItem = v } }
          //     }, child)
          //   }
          // },
          {
            prop: 'rectifyDesc',
            label: '整改项说明',
            minWidth: 200,
            render: (h, row) => {
              // <el-input v-model="formData.customerConfirmAdvice" type="textarea"
              //  :autosize="{minRows: 3}"
              //  maxlength="1024" show-word-limit placeholder="确认意见" clearable />
              if (!this.genPdf && !this.preview) {
                return [h('el-input', {
                  props: {
                    value: row.rectifyDesc,
                    type: 'textarea',
                    autosize: {
                      minRows: 1
                    },
                    maxlength: 1024,
                    showWordLimit: true,
                    placeholder: '整改项说明',
                    clearable: true
                  },
                  on: {
                    input: v => {
                      this.$set(row, 'rectifyDesc', v)
                    }
                  }
                })]
              }
              return [h('div', { style: {
                whiteSpace: 'break-spaces',
                wordBreak: 'break-all',
                width: '100%'
              }}, row.rectifyDesc)]
            }
            // edit: {
            //   canEdit: true,
            //   editType: 'text'
            // }
          }
        ]
      }
    }
  },
  computed: {
    comData() {
      const dataList = this.data.length > 0 ? this.data : this.tableData
      if (dataList.length > 0) {
        dataList.forEach(v => {
          this.$set(v, 'list', [])
          if (!v.principalCode || !v.principalName) return
          const arr1 = v.principalCode.split(',')
          const arr2 = v.principalName.split(',')
          for (let i = 0; i < arr1.length; i++) {
            v.list.push({ label: arr2[i], value: arr1[i] })
          }
        })
      }
      return dataList
    }
  },
  watch: {
    type: {
      handler() {
        this.getDetail()
      },
      immediate: true
    },
    genPdf: {
      handler(v) {
        this.$emit('gen-pdf', v)
      },
      immediate: true
    }
  },
  methods: {
    getDetail() {
      if (this.accType === 'hard') {
        this.getHardDetail()
      } else {
        this.getSoftDetail()
      }
    },
    // 设置验收结果值
    setAcceptResult(v, row) {
      const t = this.tableData.filter(e => row.configAcceptDutyId === e.configAcceptDutyId)
      if (t.some(e => ['1', 1].includes(e.haveProblem))) {
        t.forEach(e => {
          this.$set(e, 'acceptResult', 'UNQUALIFIED')
        })
      } else if (t.every(e => ['0', 0].includes(e.haveProblem))) {
        t.forEach(e => {
          this.$set(e, 'acceptResult', 'ONE_OFF')
        })
      }
    },
    // 合并表格
    tableSpanMethod({ row, column, rowIndex, columnIndex }) {
      const indexs = [1, 2, 3, 4]
      if (indexs.includes(columnIndex)) {
        if (row.rowSpan !== 0) {
          return [row.rowSpan, 1]
        } else {
          return [0, 0]
        }
      }
    },
    setPrincipalValue(row, v) {
      const cdid = row.configAcceptDutyId
      if (v.length > 0) {
        for (const item of this.tableData) {
          if (item.configAcceptDutyId === cdid) {
            this.$set(item, 'principalCode', v.map(i => i.account).join(','))
            this.$set(item, 'principalName', v.map(i => i.userName).join(','))
          }
        }
      } else {
        for (const item of this.tableData) {
          if (item.configAcceptDutyId === cdid) {
            this.$set(item, 'principalCode', '')
            this.$set(item, 'principalName', '')
          }
        }
      }
    },
    // 设置值
    setValueByCDID(row, ...args) {
      const cdid = row.configAcceptDutyId
      for (const item of this.tableData) {
        if (item.configAcceptDutyId === cdid) {
          for (const kv of args) {
            for (const [k, v] of Object.entries(kv)) {
              this.$set(item, k, v)
            }
          }
        }
      }
    },
    // 转换数据结构
    handlerData(data) {
      const t = []
      data.forEach(e => {
        const c = sortArr(e.configAcceptProblemDtos || [], 'displayOrder').flat(Infinity)
        const item = {
          // acceptType	验收类型
          // configAcceptDutyId	验收责任归属配置ID
          // createBy
          // createTime
          // id	ID
          // lastUpdateBy	string
          // lastUpdateTime	string
          // objectVersionNumber
          // problemClass	问题分类

          acceptId: this.$route.query.id,	// 门店验收ID
          acceptProblemDetailId: '',	// 验收报告问题明细表ID
          acceptResult: 'ONE_OFF',	// 验收结果
          acceptType: e.acceptType,	// 验收类型：1软装2硬装
          actualRectifyEndTime: '', // 	实际整改完成时间
          belongDuty: e.belongDuty,	// 责任归属
          configAcceptDutyId: e.id,	// 验收问题责任归属配置ID
          haveProblem: 0,	// 是否存在验收问题：0否1是
          mustRectifyEndTime: '',	// 应整改完成时间
          principalCode: '',	// 责任人编码
          principalName: '',	// 责任人名称
          problemClass: c.problemClass,	// 问题分类
          problemDesc: '',	// 验收问题说明
          problemDetailDTOList: c.map(ee => {
            return {
              // acceptDutyId: ee.configAcceptDutyId,	// 验收责任归属ID
              configAccpetProblemId: ee.id,	// 验收问题分类配置ID
              haveProblem: 0,	// 是否存在验收问题：0否1是
              // haveRectifyItem: 0,	// 是否存在整改项：0否1是
              haveRectifyItem: '',	// 是否存在整改项：0否1是
              problemDesc: '',	// 验收问题说明
              problemType: ee.problemClass,	// 问题分类：1硬装2软装3产品缺货4产品混搭57S6安装7补件
              problemClass: ee.problemType || ee.problemClass,
              rectifyDesc: '',	// 整改说明
              rectifyResult: ''	// 整改结果
            }
          }),
          problemType: '',	// 问题分类：1硬装2软装3产品缺货4产品混搭57S6安装7补件
          rectifyTaskCode: ''	// 整改任务号
        }
        t.push(item)
      })
      return t
    },
    // 硬装验收
    getHardDetail() {
      const { id } = this.$route.query
      getProblemDetailList(id, this.type).then(res => {
        const data = res.data || []
        if (data.length === 0) {
          getDutyAndProblemlist().then(res => {
            const data = res.data.filter(e => {
              return e.acceptType.toUpperCase() === this.type.toUpperCase()
            })
            this.tableData = this.handlerTableData(this.handlerData(data))
          })
        } else {
          this.tableData = this.handlerTableData(data)
        }
      })
    },
    // 软装验收
    getSoftDetail() {
      // 软装验收保存之后 再次进入编辑 显示数据有问题 有问题才显示整改时间
      const { id } = this.$route.query
      getSoftProblemList(id).then(res => {
        const data = res.data || []
        if (data.length === 0) {
          getDutyAndProblemlist().then(res => {
            const data = res.data.filter(e => {
              return e.acceptType.toUpperCase() === this.type.toUpperCase()
            })
            this.tableData = this.handlerTableData(this.handlerData(data))
          })
        } else {
          this.tableData = this.handlerTableData(data)
        }
      })
    },
    showMustRectifyEndTime(row) {
      for (const item of this.tableData) {
        if (item.configAcceptDutyId === row.configAcceptDutyId && (item.haveProblem === 1 || item.haveProblem === '1')) {
          return true
        }
      }
      return false
    },
    // 处理数据
    handlerTableData(data) {
      const t = []
      data.forEach(e => {
        const problemDetailDTOList = e.problemDetailDTOList || []
        delete e.problemDetailDTOList
        problemDetailDTOList.forEach((p, i) => {
          const tmp = {
            ...e,
            ...p,
            rowSpan: 0
          }
          tmp.haveProblem = tmp.haveProblem || 0
          if (i === 0) {
            tmp.rowSpan = problemDetailDTOList.length
          }
          if (this.type === 'hard') {
            let belongDuty
            if (tmp.belongDuty === '门头') {
              belongDuty = 'DOOR'
            } else if (tmp.belongDuty === '卖场') {
              belongDuty = 'STORES'
            }
            if ((this.range || '').includes(belongDuty)) {
              t.push(tmp)
            }
          } else {
            t.push(tmp)
          }
        })
      })
      return t
    },
    // 生成提交数据
    genData() {
      const data = []
      const t = {}
      for (let i = 0; i < this.tableData.length; i++) {
        const v = this.tableData[i]
        if (v.haveProblem === '' || v.haveProblem === undefined) {
          this.$message.warning(`请选择第${i + 1}行是否存在问题！`)
          return Promise.reject('')
        }
        if (v.acceptResult === 'UNQUALIFIED') {
          if (v.principalCode === '' || v.principalCode === undefined) {
            this.$message.warning(`请选择${v.belongDuty}责任人！`)
            return Promise.reject('')
          }
          if ([1, '1'].includes(v.haveProblem) && (v.mustRectifyEndTime === '' || v.mustRectifyEndTime === undefined)) {
            this.$message.warning(`请选择${v.belongDuty}应整改完成时间！`)
            return Promise.reject('')
          }
          // if (v.rectifyDesc === '' || v.rectifyDesc === undefined) {
          //   this.$message.warning(`请输入第${i + 1}行整改项说明！`)
          //   return Promise.reject('')
          // }
        }
        if ((v.haveProblem || '').toString() === '1') {
          if (v.problemDesc === '' || v.problemDesc === undefined) {
            this.$message.warning(`请输入第${i + 1}行验收问题说明！`)
            return Promise.reject('')
          }
        }
        const key = v.configAcceptDutyId
        if (!t[key]) {
          t[key] = []
        }
        t[key].push(v)
      }
      // this.tableData.forEach(e => {
      //   const key = e.configAcceptDutyId
      //   if (!t[key]) {
      //     t[key] = []
      //   }
      //   t[key].push(e)
      // })
      for (const [k, v] of Object.entries(t)) {
        if (v.length === 0) continue
        const item = v[0]
        data.push({
          acceptId: item.acceptId || this.$route.query.id,	// 门店验收ID
          acceptProblemDetailId: item.acceptProblemDetailId || '',	// 验收报告问题明细表ID
          acceptResult: item.acceptResult,	// 验收结果
          acceptType: item.acceptType,	// 验收类型：1软装2硬装
          actualRectifyEndTime: item.actualRectifyEndTime || '', // 	实际整改完成时间
          belongDuty: item.belongDuty,	// 责任归属
          configAcceptDutyId: item.configAcceptDutyId,	// 验收问题责任归属配置ID
          // haveProblem: 0,	// 是否存在验收问题：0否1是
          mustRectifyEndTime: item.mustRectifyEndTime,	// 应整改完成时间
          principalCode: item.principalCode,	// 责任人编码
          principalName: item.principalName,	// 责任人名称
          problemClass: item.problemClass,	// 问题分类
          problemDesc: item.problemDesc,	// 验收问题说明
          problemDetailDTOList: v.map(ee => {
            return {
              // acceptDutyId: ee.configAcceptDutyId,	// 验收责任归属ID
              configAccpetProblemId: ee.configAccpetProblemId,	// 验收问题分类配置ID
              haveProblem: ee.haveProblem,	// 是否存在验收问题：0否1是
              haveRectifyItem: ee.haveRectifyItem,	// 是否存在整改项：0否1是
              problemDesc: ee.problemDesc,	// 验收问题说明
              problemType: ee.problemClass || ee.problemType,	// 问题分类：1硬装2软装3产品缺货4产品混搭57S6安装7补件
              rectifyDesc: ee.rectifyDesc,	// 整改说明
              rectifyResult: ee.rectifyResult || '',	// 整改结果
              id: ee.id || ''
            }
          }),
          problemType: item.problemType || '',	// 问题分类：1硬装2软装3产品缺货4产品混搭57S6安装7补件
          rectifyTaskCode: item.rectifyTaskCode || ''	// 整改任务号
        })
      }
      return Promise.resolve(data)
    },
    // 生成报告隐藏多余数据
    hiddeHtml() {
      const genPdf = document.querySelector('#gen-pdf')
      const hides = genPdf.querySelectorAll("[gen-pdf='gen-pdf-hide']")
      for (const item of hides) {
        if (this.genPdf) {
          item.dataset.display = item.style.display
          item.style.display = 'none'
        } else {
          item.style.display = item.dataset.display || 'initial'
        }
      }
    },
    // 生成整改指令单
    clickPdfHandle() {
      this.$emit('save', 'rectify')
      // const routeUrl = this.$router.resolve({
      //   path: '/printReport',
      //   query: { id: this.$route.query.id, type: 'rectify' }
      // })
      // window.open(routeUrl.href, '_blank')
      // this.showPrint = true
    },
    // 生成验收报告
    clickGenHandle() {
      this.$emit('save', this.$route.query.acceptType || 'HARD')// 生成报告之前，保存操作数据
      // const routeUrl = this.$router.resolve({
      //   path: '/printReport',
      //   query: { id: this.$route.query.id, type: this.$route.query.acceptType || 'HARD' }
      // })
      // window.open(routeUrl.href, '_blank')
      // this.showPrint = true
    }
  }
}
</script>
<style lang="scss" scoped>
.problem-detail{
  /deep/ .el-tooltip .table-other span{
    display: inline-block;
  }
  .gen-pdf-style{
    white-space: break-spaces;
    word-break: break-all;
    width: 100%;
  }
}
</style>
